package com.practices.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUtil {
	private static final String CHARSET = HTTP.UTF_8;
	private static HttpClient customerHttpClient;

	public static synchronized HttpClient getHttpClient() {

		if (null == customerHttpClient) {
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) " + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 超时设置
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, 1000);
			/* 连接超时 */
			HttpConnectionParams.setConnectionTimeout(params, 2000);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, 4000);
			// 设置我们的HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
			customerHttpClient = new DefaultHttpClient(conMgr, params);
		}
		return customerHttpClient;
	}

	// 上传string，返回string
	public static String getDataDownUsePOST(String url, String strbody) {
		HttpClient httpClient = getHttpClient();
		HttpPost httpPost = new HttpPost(url);
		try {
			StringBody strbodyString = new StringBody(strbody, Charset.forName("utf-8"));
			MultipartEntity multipartEntity = new MultipartEntity();
			multipartEntity.addPart("strbody", strbodyString);
			httpPost.setEntity(multipartEntity);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String strResultString = EntityUtils.toString(httpResponse.getEntity());
				return strResultString;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// post 请求和http连接池的关闭
			// httpPost.abort();
			// httpClient.getConnectionManager().shutdown();
		}
		return null;
	}

	// post请求下载返回inputStream
	public static InputStream postDataForIO(String url) {
		InputStream is;
		HttpClient httpClient = getHttpClient();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			try {
				is = httpResponse.getEntity().getContent();
				return is;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// httpPost.abort();
				// httpClient.getConnectionManager().shutdown();
			}
		} else {
			Util.log("状态码不为200");
		}
		return null;
	}

	
	public static byte[] postDataForIObytes(String url) {
		HttpClient httpClient = getHttpClient();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse httpResponse = null;

		try {
			httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// is = httpResponse.getEntity().getContent();
				byte[] result = EntityUtils.toByteArray(httpResponse.getEntity());
				return result;
				// httpPost.abort();
				// httpClient.getConnectionManager().shutdown();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public static byte[] getDataForIObytes(String url) {
		HttpClient httpClient = getHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		
		byte[] result=null;

		try {
			httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				Util.log(httpResponse.getStatusLine().getStatusCode());
				// is = httpResponse.getEntity().getContent();
				HttpEntity httpEntity=httpResponse.getEntity();
				if (httpEntity!=null&httpEntity.isStreaming()) {
					String contentType =httpEntity.getContentType().toString();
					Util.log(contentType);
					result = EntityUtils.toByteArray(httpResponse.getEntity());
					Util.log(result);
					return result;
				
				}else{
					Util.log(result);
					return null;
				}
				// httpPost.abort();
				// httpClient.getConnectionManager().shutdown();
			}else{
				Util.log(httpResponse.getStatusLine().getStatusCode());
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	// public static byte[] postDataForIO(String url){
	// InputStream is=postDataForIO(url);
	// Byte[] buff=EntityUtils.toByteArray(entity)
	// }

	public static InputStream getDataForIO(String url) {
		InputStream is;
		HttpClient httpClient = getHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			try {
				is = httpResponse.getEntity().getContent();
				return is;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// httpGet.abort();
				// httpClient.getConnectionManager().shutdown();
			}

		} else {
			Util.log("状态码不为200");
		}
		return null;
	}

	public static String postDataForStr(String url) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
			Util.log("******************" + "ClientProtocolException");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			try {
				String str = EntityUtils.toString(httpResponse.getEntity());
				Util.log(str);
				return str;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// httpPost.abort();
				// httpClient.getConnectionManager().shutdown();
			}

		} else {
			Util.log("状态码不为200" + httpResponse.getStatusLine().getStatusCode());
		}
		return null;
	}

	public static String getDataForStr(String url) {
		HttpClient httpClient = getHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
		} catch (ClientProtocolException e) {
			Util.log("******************" + "ClientProtocolException");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			try {
				String str = EntityUtils.toString(httpResponse.getEntity());
				Util.log(str);
				return str;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// httpGet.abort();
				// httpClient.getConnectionManager().shutdown();
			}

		} else {
			Util.log("状态码不为200" + httpResponse.getStatusLine().getStatusCode());
		}
		return null;
	}

//	public static boolean isNetworkAvailable(Context context) {
//		boolean result = false;
//		if (null != context) {
//			ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//			NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
//
//			if (null != networkInfo) {
//				result = networkInfo.isAvailable();
//			}
//		}
//
//		return result;
//	}

	public static boolean isWifiWorking(Context context) {
		if (null == context) {
			return false;
		}
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		return ((null != networkInfo) && (ConnectivityManager.TYPE_WIFI == networkInfo.getType()));
	}

	public static String getNetType(Context context) {
		try {
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService("connectivity");
			NetworkInfo info = cm.getActiveNetworkInfo();
			String typeName = "";
			if (info != null) {
				typeName = info.getTypeName().toLowerCase();
				if (typeName.equals("mobile")) {
					typeName = info.getExtraInfo().toUpperCase();
				}
			}
			return typeName.toUpperCase();
		} catch (Exception e) {
			LogUtil.e("NearMeStatistics", e);
		}
		return "0";
	}
	
	
	public static enum netType {
		wifi, CMNET, CMWAP, noneNet
	}

	/**
	 * 网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断是否有网络连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 判断WIFI网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isWifiConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mWiFiNetworkInfo != null) {
				return mWiFiNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 判断MOBILE网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isMobileConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (mMobileNetworkInfo != null) {
				return mMobileNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 获取当前网络连接的类型信息
	 * 
	 * @param context
	 * @return
	 */
	public static int getConnectedType(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
			if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
				return mNetworkInfo.getType();
			}
		}
		return -1;
	}

	/**
	 * 
	 * @author 白猫
	 * 
	 *         获取当前的网络状态 -1：没有网络 1：WIFI网络2：wap 网络3：net网络
	 * 
	 * @param context
	 * 
	 * @return
	 */
	public static netType getAPNType(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType.noneNet;
		}
		int nType = networkInfo.getType();

		if (nType == ConnectivityManager.TYPE_MOBILE) {
			if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
				return netType.CMNET;
			}
			else {
				return netType.CMWAP;
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			return netType.wifi;
		}
		return netType.noneNet;

	}
}